Ext.BLANK_IMAGE_URL = '/scripts/ext/resources/images/default/s.gif';

var tasks = {
    sessURL  : '/apps/notex/services/security/session.jsx',
    taskURL  : '/apps/notex/services/admin/tasks.jsx',
    grid     : null,
    isInsert : false
};

tasks.login = function(values) {

    // Get the username and password
    var username = values.username;
    var password = values.password;

    Ext.Ajax.request({
        url : tasks.sessURL,
        params : {
            username : username,
            password : password,
        },
        callback : function(options, ok, res) { tasks.load(res); }
    });
}

tasks.load = function(res) {

    var error = Ext.DomQuery.selectValue('error message', res.responseXML);
    if (error) {
        login.win.setTitle(error);
        login.win.show();
        return;
    }

    Ext.QuickTips.init();

    function formatDate(value){
        return value ? value.dateFormat('M d, Y') : '';
    };

    // shorthand alias
    var fm = Ext.form;

    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store (created below)
    var cm = new Ext.grid.ColumnModel([{
            id : 'id',
            header : "Id",
            dataIndex : 'id',
            width : 20,
            format : 'fix'
        },{
            header : "Summary",
            dataIndex : 'summary',
            width : 200,
            editor : new fm.TextField({
                allowBlank : false
            })
        },{
            header : "Description",
            dataIndex : 'description',
            width : 400,
            editor : new fm.TextField({
                allowBlank : false
            })
        },{
            header : "Deliver on",
            dataIndex : 'deliver_on',
            width : 95,
            renderer : formatDate,
            editor : new fm.DateField({
                format : 'd/m/y',
                minValue : '01/01/09',
                disabledDays : [0, 6],
                disabledDaysText : 'Tasks are not completed on the weekends'
            })
        }
    ]);

    // by default columns are sortable
    cm.defaultSortable = true;

    // this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    var Task = Ext.data.Record.create([
           // the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name : 'id', type : 'int'},
           {name : 'summary', type : 'string'},
           {name : 'description', type : 'string'},
           {name : 'deliver_on', type : 'date', dateFormat : 'Y-m-d'}
      ]);

    // create the Data Store
    var store = new Ext.data.Store({
        url : tasks.taskURL,
        reader : new Ext.data.XmlReader({ record : 'object' }, Task),
        sortInfo : {field : 'id', direction : 'ASC'}
    });

    // save updates
    store.addListener('update', function(store) {
        var mods = store.getModifiedRecords();
        for (var i = 0; i < mods.length; i++) {
            var record = mods[i];
            var task = record.getChanges();
            task.id = record.get('id');
            if (!task.id && tasks.isInsert) continue;
            tasks.save(task);
            record.dirty = false;
        }
    });

    // create the editor grid
    tasks.grid = new Ext.grid.EditorGridPanel({
        store : store,
        cm : cm,
        renderTo : 'tasks-grid',
        width : 1000,
        height : 600,
        autoExpandColumn : 'id',
        title : 'Task Manager',
        frame : true,
        clicksToEdit : 1,

        tbar : [{
            text : 'Add Task',
            handler : function(){
                var task = new Task({
                    id : 0,
                    summary : '',
                    description : '',
                    deliver_on : (new Date()).clearTime()
                });
                tasks.grid.stopEditing();
                store.insert(0, task);
                tasks.grid.startEditing(0, 0);
            }
        }]
    });

    // trigger the data store load
    store.load();
}

// Save an updated record
tasks.save = function(task) {
    var action = task.id ? 'update' : 'insert';

    // Only insert one at a time
    if (action == 'insert') {
        if (tasks.isInsert) return;
        tasks.isInsert = true;
    }

    if (task.deliver_on) task.deliver_on = task.deliver_on.format('Y-m-d');
    Ext.Ajax.request({
        url : tasks.taskURL,
        params : {
            action : action,
            task : Ext.util.JSON.encode(task)
        },
        callback : function(options, ok, res) { tasks.sync(res); }
    });
}

// Sync the response with the data source
tasks.sync = function(res) {

    // Find the insert ID in the response XML (not pretty!)
    var match = res.responseText.match(/insert_id="(\d+)"/);
    if (!match[1]) return;

    // Update the ID of the inserted record
    tasks.grid.store.each( function(record) {
        if (record.get('id') == 0) {
            record.set('id', match[1]);
            tasks.isInsert = false;
        }
    });
}

// END
